package com.demon.auto.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

/**
 * 发送邮件工具类
 *
 * @author huangrz
 * @version 1.0
 * @date 2025/02/13 14:09
 */
@Slf4j
@Component
public class EmailUtils {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String senderEmailAddr;


    /**
     * 发送签到失败通知邮件
     *
     * @param receiveEmail 收件人邮箱地址
     * @param clientName   客户端名称
     */
    public void sendClientOfflineMail(String receiveEmail, String clientName) {
        sendSimpleEmailAsync(receiveEmail,
                "Demon Auto Client Offline Notice",
                "[" + LocalDateUtil.formatLocalDateTime(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss")
                        + "] 客户端 " + clientName + " 已掉线，请检查客户端的网络是否正常！");
    }

    /**
     * 发送验证码邮件
     *
     * @param receiveEmail 收件人邮箱地址
     * @param code         验证码
     */
    public boolean sendVerificationCodeEmail(String receiveEmail, String code) {
        return sendSimpleEmail(receiveEmail, "Demon Auto Verification Code",
                "您的账号正在修改敏感信息，请确认是否为本人操作，请勿泄露验证码，验证码（有效期5分钟）：" + code);
    }

    /**
     * 发送签到成功通知邮件
     *
     * @param receiveEmail 收件人邮箱地址
     * @param signTime     签到时间
     */
    public void sendSignSuccessMail(String receiveEmail, LocalDateTime signTime) {
        sendSimpleEmailAsync(receiveEmail,
                "Demon Auto Sign Success Notice",
                "今日份签到成功！签到时间：" + LocalDateUtil.formatLocalDateTime(signTime, "yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 发送签到失败通知邮件
     *
     * @param receiveEmail 收件人邮箱地址
     * @param msg          错误提示
     */
    public void sendSignErrorMail(String receiveEmail, String msg) {
        sendSimpleEmailAsync(receiveEmail,
                "Demon Auto Sign Error Notice",
                "[" + LocalDateUtil.formatLocalDateTime(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss")
                        + "] 签到任务执行异常：" + msg);
    }

    /**
     * 异步发送简单文本邮件
     *
     * @param receiveEmail 收件人邮箱地址
     * @param subject      邮件主题
     * @param content      邮件内容
     */
    public void sendSimpleEmailAsync(String receiveEmail, String subject, String content) {
        CompletableFuture.runAsync(() -> sendSimpleEmail(receiveEmail, subject, content));
    }

    /**
     * 发送简单文本邮件
     *
     * @param receiveEmail 收件人邮箱地址
     * @param subject      邮件主题
     * @param content      邮件内容
     */
    public boolean sendSimpleEmail(String receiveEmail, String subject, String content) {
        if (StringUtils.isBlank(receiveEmail)) {
            log.error("收件人邮箱地址为空！");
            return false;
        }
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(senderEmailAddr);
            helper.setTo(receiveEmail);
            helper.setSubject(subject);
            helper.setText(content, true);
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("邮件发送失败！", e);
            return false;
        }
        return true;
    }

    /**
     * 发送带附件的邮件
     *
     * @param receiveEmail 收件人邮箱地址
     * @param subject      邮件主题
     * @param content      邮件内容
     * @param filePath     附件文件路径
     */
    public boolean sendEmailWithAttachment(String receiveEmail, String subject, String content, String filePath) {
        if (StringUtils.isBlank(receiveEmail)) {
            log.error("收件人邮箱地址为空！");
            return false;
        }
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(senderEmailAddr);
            helper.setTo(receiveEmail);
            helper.setSubject(subject);
            helper.setText(content, true);

            // 添加附件
            helper.addAttachment("附件名称", new java.io.File(filePath));

            javaMailSender.send(mimeMessage);
            log.info("邮件发送成功！收件人：{}, 主题：{}", receiveEmail, subject);
        } catch (Exception e) {
            log.error("带附件的邮件发送失败！", e);
            return false;
        }
        return true;
    }

}